/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.web.servlet;

import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.InitialContext;

/**
 * @Author kent
 */
public class CacheSyncTopicSender {

	private static final String TOPIC = "han.bashe.sync.Topic";
	private static final String FAC = "han.bashe.gateway.fac";

	public static void send(String xml) throws Exception {

		InitialContext ctx = null;
		TopicConnectionFactory tconFactory = null;
		TopicConnection tcon = null;
		TopicSession tsession = null;
		TopicPublisher tpublisher = null;
		Topic topic = null;
		TextMessage msg = null;

		try {
			ctx = new InitialContext();
			tconFactory = (TopicConnectionFactory) ctx.lookup(FAC);
			tcon = tconFactory.createTopicConnection();
			tsession = tcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
			topic = (Topic) ctx.lookup(TOPIC);
			tpublisher = tsession.createPublisher(topic);

			msg = tsession.createTextMessage();
			tcon.start();
			msg.setText(xml);
			
			 tpublisher.publish(msg);
             

		} finally {
			 try{
	                if(tpublisher != null)
	                    tpublisher.close();
	                if(tsession != null)
	                    tsession.close(); 
	                if(tcon != null){
	                    //qcon.stop();
	                    tcon.close();
	                }
	                if(ctx != null)
	                    ctx.close();
	            }catch(Exception e){}    
		}

	}

}
